package com.atguigu.gulimail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryBrandRelationService;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.gulimail.product.vo.Catalog2Vo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listwithtree() {

        //1。查询所有的分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> Level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildren(menu, entities));
                    return menu;
                })
                .sorted(Comparator.comparingInt(menu -> Optional.ofNullable(menu.getSort()).orElse(0)))
                .collect(Collectors.toList());

        return Level1Menus;
    }


    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {



        List<CategoryEntity> collect = all.stream()
                .filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                })
                .map(categoryEntity -> {

                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted(Comparator.comparingInt(menu -> Optional.ofNullable(menu.getSort()).orElse(0)))
                .collect(Collectors.toList());

        return collect;
    }


    @Override
    public void removeMenuByIds(List<Long> asList) {

        //TODO  1，检查当前删除的菜单，是否被别处引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);

    }

    @Override
    public Long[] findCategoryPath(Long id) {

        List<Long> list = new ArrayList<>();

        Long[] findpath = findpath(id, list);

        return findpath;

    }

    @CacheEvict(value = "category",allEntries = true)
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {

        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());


    }

    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getOneCategory() {

        System.out.println("查数据库了、、、、");
        List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));

        return list;
    }

    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public Map<String, List<Catalog2Vo>> getCatelogJson() {

        System.out.println("查询了数据库");

        //优化：一次性查出所有数据
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> rootCategory = getParent_cid(entities, 0L);

        //封装数据
        Map<String, List<Catalog2Vo>> map = rootCategory.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), (l2) -> {

            List<CategoryEntity> L2Category = getParent_cid(entities, l2.getCatId());

            List<Catalog2Vo> catalog2Vos = L2Category.stream().map(l3 -> {

                Catalog2Vo catalog2Vo = new Catalog2Vo();
                catalog2Vo.setCatalog1Id(l2.getCatId().toString());
                catalog2Vo.setId(l3.getCatId().toString());
                catalog2Vo.setName(l3.getName());

                List<CategoryEntity> catalog3Entity = getParent_cid(entities, l3.getCatId());

                List<Catalog2Vo.catalog3Vo> catalog3Vos = catalog3Entity.stream().map((item) -> {

                    Catalog2Vo.catalog3Vo catalog3Vo = new Catalog2Vo.catalog3Vo();

                    catalog3Vo.setCatalog2Id(l3.getCatId().toString());
                    catalog3Vo.setId(item.getCatId().toString());
                    catalog3Vo.setName(item.getName());

                    return catalog3Vo;

                }).collect(Collectors.toList());

                catalog2Vo.setCatalog3List(catalog3Vos);

                return catalog2Vo;

            }).collect(Collectors.toList());

            return catalog2Vos;
        }));

        return map;

    }



    public Map<String, List<Catalog2Vo>> getCatelogJsonRedis() {

        String uuid = UUID.randomUUID().toString();

        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock",uuid, 30,TimeUnit.SECONDS);

        if (lock) {
            System.out.println("获取分布式锁成功...");
            Map<String, List<Catalog2Vo>> catelogJsonFromDb;
            try{
                catelogJsonFromDb = getCatelogJsonFromDb();
            }finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList("lock"), uuid);
            }
            return catelogJsonFromDb;
        }else{
            System.out.println("获取分布式锁失败...等待重试");
            try{
//                Thread.sleep(200);
            }catch (Exception e){
            }
            return getCatelogJsonRedis();
        }
    }


    public Map<String, List<Catalog2Vo>> getCatelogJsonWithRedis() {

        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)) {

            Map<String, List<Catalog2Vo>> catelogJsonFromDb = getCatelogJsonFromDb();
            String s = JSON.toJSONString(catelogJsonFromDb);
            redisTemplate.opsForValue().set("catelogJson",s);
            return catelogJsonFromDb;
        }

        Map<String, List<Catalog2Vo>> stringListMap = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return stringListMap;
    }


    public Map<String, List<Catalog2Vo>> getCatelogJsonFromDb() {

        String catelogJson = redisTemplate.opsForValue().get("catelogJson");
        if (!StringUtils.isEmpty(catelogJson)) {

            Map<String, List<Catalog2Vo>> s = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });

            return s;
        }

        System.out.println("查询了数据库");

        //优化：一次性查出所有数据
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //查出所有1级分类
        List<CategoryEntity> rootCategory = getParent_cid(entities, 0L);

        //封装数据
        Map<String, List<Catalog2Vo>> map = rootCategory.stream().collect(Collectors.toMap(l1 -> l1.getCatId().toString(), (l2) -> {

            List<CategoryEntity> L2Category = getParent_cid(entities, l2.getCatId());

            List<Catalog2Vo> catalog2Vos = L2Category.stream().map(l3 -> {

                Catalog2Vo catalog2Vo = new Catalog2Vo();
                catalog2Vo.setCatalog1Id(l2.getCatId().toString());
                catalog2Vo.setId(l3.getCatId().toString());
                catalog2Vo.setName(l3.getName());

                List<CategoryEntity> catalog3Entity = getParent_cid(entities, l3.getCatId());

                List<Catalog2Vo.catalog3Vo> catalog3Vos = catalog3Entity.stream().map((item) -> {

                    Catalog2Vo.catalog3Vo catalog3Vo = new Catalog2Vo.catalog3Vo();

                    catalog3Vo.setCatalog2Id(l3.getCatId().toString());
                    catalog3Vo.setId(item.getCatId().toString());
                    catalog3Vo.setName(item.getName());

                    return catalog3Vo;

                }).collect(Collectors.toList());

                catalog2Vo.setCatalog3List(catalog3Vos);

                return catalog2Vo;

            }).collect(Collectors.toList());

            return catalog2Vos;
        }));

        return map;

    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> list, Long l2) {

        List<CategoryEntity> collect = list.stream().filter(item -> item.getParentCid() == l2).collect(Collectors.toList());

        return collect;
    }


    private Long[] findpath(Long id, List<Long> list) {

        list.add(id);

        CategoryEntity categoryEntity = this.getById(id);
        if (categoryEntity.getParentCid() != 0) {
            findpath(categoryEntity.getParentCid(), list);
        }

        Collections.reverse(list);

        return list.toArray(new Long[list.size()]);
    }

}